package com.zhaoziqian.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhaoziqian.model.AdminModel;
import com.zhaoziqian.model.CAModel;
import com.zhaoziqian.model.OrdererModel;
import com.zhaoziqian.model.PeerModel;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static com.zhaoziqian.config.Config.*;

/**
 * Created with fabric-cli
 * 作者： zhaoziqian
 * 时间： 2018/5/28  下午11:05
 * 功能：
 */
@Component
public class ReadNetworkConfig {

    private static final Logger logger = LoggerFactory.getLogger(ReadNetworkConfig.class);

    public static String NETWORK_FILE_PATH;
    public static String NETWORK_FILE_NAME;
    public static JSONObject networkConfigJson = null;

    @Value("${network-config.file.path}")
    private String networkFilePathTmp;
    @Value("${network-config.file.name}")
    private String networkFileNameTmp;

    @PostConstruct
    public void init(){

        NETWORK_FILE_PATH = networkFilePathTmp;
        NETWORK_FILE_NAME = networkFileNameTmp;

        File networkConfig = new File(NETWORK_FILE_PATH + NETWORK_FILE_NAME);
        if (!networkConfig.exists()) {
            logger.error("The '{}' was not found !!! Please upload '{}' file in '{}'",NETWORK_FILE_NAME,NETWORK_FILE_NAME,NETWORK_FILE_PATH);
            throw new RuntimeException("Can't found " + NETWORK_FILE_NAME);
        }
        FileInputStream fis = null;
        String netConfig = null;
        try {
            fis = new FileInputStream(networkConfig);
            netConfig = IOUtils.toString(fis,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (netConfig != null){
            networkConfigJson = JSON.parseObject(netConfig);
            logger.debug(networkConfigJson.toJSONString());
        }
    }

    public static OrdererModel getOrderer(String org,String ordererId){

        logger.info("get orderer info by {}.{}" ,org,ordererId);
        String result = getParam(NETWORK_CONFIG,ORDERER,org,ordererId);
        if (StringUtils.isEmpty(result)){
            throw new RuntimeException("Can't found orderer by {"+ org +"}.{"+ ordererId +"}");
        }
        OrdererModel ordererModel = JSON.parseObject(result,OrdererModel.class);

        return ordererModel;
    }

    public static PeerModel getPeer(String org,String peerId) throws RuntimeException {

        logger.debug("get peer info by {}.{}" ,org,peerId);
        String result = getParam(NETWORK_CONFIG,PEER,org,peerId);
        if (StringUtils.isEmpty(result)){
            throw new RuntimeException("Can't found peer by {"+ org +"}.{"+ peerId +"}");
        }
        PeerModel peerModel = JSON.parseObject(result,PeerModel.class);

        return peerModel;
    }

    public static AdminModel getAdmin(boolean isOrderer,String org){
        String result = "";
        AdminModel adminModel = null;
        String node = isOrderer?ORDERER:PEER;
//        if (isOrderer) {
//            result = getParam(NETWORK_CONFIG,ORDERER,org,ADMIN);
//        } else {
//            result = getParam(NETWORK_CONFIG,PEER,org,ADMIN);
//        }
        result = getParam(NETWORK_CONFIG,node,org,ADMIN);
        if (StringUtils.isEmpty(result)){
            throw new RuntimeException("Can't found admin by {"+ node +"}.{"+ org +"}.");
        }
        adminModel = JSON.parseObject(result,AdminModel.class);
        return adminModel;
    }

    public static CAModel getCA(String org){
        String result = getParam(NETWORK_CONFIG,PEER,org,CA);
        if (StringUtils.isEmpty(result)){
            throw new RuntimeException("Can't found ca by {"+ org +"}.");
        }
        return JSON.parseObject(result,CAModel.class);
    }

    public static String getParam(String... params ){
        return getParam(networkConfigJson,params);
    }

    public static String getParam(JSONObject json ,String... params ){
        String temp = "";
        JSONObject jsonTemp = json;
        int index = params.length;
        for (String param: params){

            temp = jsonTemp.getString(param);
            if (--index <= 0){
                logger.debug("The json targer result is {}",temp);
                return temp;
            }
            jsonTemp = JSON.parseObject(temp);
        }

        logger.debug("The json targer result is {}",jsonTemp.toJSONString());

        return jsonTemp.toJSONString();
    }
}
